(function() {
  var VERSION, adHtml, capture, deleta, executed, firstTabId, getServerKey, indexUrl, leftView, reply, serverData, serverUrl, showOneCapture, showOrderPop, submitTimes, uiData,
    __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

  VERSION = 20131123;

  serverUrl = 'http://visitveb.duapp.com/index.php?s=';

  serverData = {};

  getServerKey = function() {
    var retry;
    retry = function(times) {
      if (times == null) {
        times = 5;
      }
      if (!times--) {
        if (confirm('系统忙！是否重试？')) {
          getServerKey();
        } else {
          return false;
        }
      }
      return $.ajax("" + serverUrl + "Order/add", {
        dataType: 'json',
        cache: false,
        data: {
          t: new Date().getTime()
        },
        error: function() {
          return setTimeout(function() {
            return retry(times);
          }, 2000);
        },
        success: function(data) {
          var textarea;
          serverData = data;
          textarea = $('#popMsgBox').show().find('textarea').val(data.msg);
          $('#openLink').attr('href', data.url);
          console.debug('get server data', data);
          chrome.windows.create({
            url: ['http://www.taobao.com'],
            focused: false,
            width: 970
          });
          return $('#screenContain').empty();
        }
      });
    };
    return retry();
  };

  capture = function(tab) {
    console.debug(new Date().toLocaleTimeString());
    console.count("capture order" + submitTimes + " screen is");
    return chrome.tabs.update(tab.tabId, {
      active: true
    }, function() {
      return chrome.tabs.captureVisibleTab(tab.windowId, function(img) {
        return clipImg(img);
      });
    });
  };

  showOneCapture = function(img) {
    var $item, html;
    html = "<div class=\"imgItem\">\n	<image src=\"" + img + "\" />\n	<span class=\"itemTime\">" + (new Date().toLocaleString()) + "</div>\n</div>";
    $item = $(html);
    $('#screenContain').append($item);
    return $item[0].scrollIntoView();
  };

  showOrderPop = function() {
    var notification;
    chrome.tabs.update(firstTabId, {
      active: true
    });
    notification = webkitNotifications.createNotification('images/notification.png', '亲可以下单了', '亲可以下单了');
    notification.show();
    return notification.onclick = function() {
      chrome.tabs.update(firstTabId, {
        active: true
      });
      return notification.close();
    };
  };

  executed = false;

  leftView = 0;

  firstTabId = 0;

  submitTimes = 0;

  indexUrl = '';

  reply = function() {
    var clickedIds, listener;
    listener = {};
    clickedIds = [];
    leftView = parseInt($('#otherGoodsNum').val());
    submitTimes++;
    firstTabId = 0;
    indexUrl = '';
    if (executed) {
      return false;
    }
    chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
      var $ele, has, i, ik, iv, k, obj, ret, tabid, v, _i, _j, _len, _len1, _ref, _ref1;
      ret = {};
      has = false;
      if (request) {
        for (k in request) {
          v = request[k];
          $ele = $('#' + k);
          if ($ele.size()) {
            if ('checkbox' === $ele.attr('type') && !$ele.attr('checked')) {
              continue;
            }
            has = true;
            ret[k] = $ele.val();
            if ('number' === $ele.attr('type')) {
              ret[k] = parseInt(ret[k]);
            }
          }
          if ('clickId' === k) {
            clickedIds.push(v);
          }
          if ('clickedIds' === k) {
            ret[k] = clickedIds;
            has = true;
          }
          if ('leftView' === k) {
            ret[k] = leftView--;
            has = true;
          }
          if ('indexUrl' === k) {
            if (("" + v).length < 12) {
              ret[k] = indexUrl;
              has = false;
            } else {
              indexUrl = v;
            }
          }
          if ('firstTabId' === k) {
            ret['firstTabId'] = firstTabId;
            has = true;
            if (true === v) {
              firstTabId = sender.tab.id;
            } else if (sender.tab.id === firstTabId) {
              ret['firstTabId'] = 0;
            }
          }
          if ('listener' === k) {
            for (_i = 0, _len = v.length; _i < _len; _i++) {
              i = v[_i];
              if (!listener[i]) {
                listener[i] = [];
              }
              if (_ref = sender.tab.id, __indexOf.call(listener[i], _ref) < 0) {
                listener[i].push(sender.tab.id);
              }
            }
          }
          if ('dispatch' === k) {
            if (v != null ? v.firstViewComplete : void 0) {
              showOrderPop();
            }
            for (ik in v) {
              iv = v[ik];
              if (listener[ik]) {
                _ref1 = listener[ik];
                for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
                  tabid = _ref1[_j];
                  obj = {};
                  obj[ik] = iv;
                  chrome.tabs.sendRequest(tabid, {
                    buy: obj
                  });
                }
              }
            }
          }
          if ('capture' === k) {
            capture(sender.tab);
            if (typeof sendRequest === "function") {
              sendRequest({
                buy: {
                  capture: 1
                }
              });
            }
          }
        }
      }
      if (has) {
        return typeof sendResponse === "function" ? sendResponse({
          buy: ret
        }) : void 0;
      }
    });
    return executed = true;
  };

  $('form').submit(function() {
    reply();
    getServerKey();
    uiData(true);
    return false;
  });

  $('#compare').change(function() {
    return $('#enterNo').val(this.value * 1 + 1);
  });

  $('#copy').live('click', function() {
    var textarea;
    textarea = $('#popMsgBox textarea');
    textarea.focus();
    document.execCommand('SelectAll');
    return document.execCommand("Copy", false, null);
  });

  adHtml = '';

  $.getJSON("" + serverUrl + "Ad/item", function(data) {
    adHtml = data.html;
    return $('#adContent').val(adHtml);
  });

  deleta = 0;

  $('#noAd').click(function() {
    var obj;
    obj = [
      {
        txt: '打开广告',
        html: ''
      }, {
        txt: '关闭广告',
        html: adHtml
      }
    ];
    deleta = deleta % 2;
    $('#adContent').val(obj[deleta].html);
    return $(this).text(obj[deleta++].txt);
  });

  uiData = function(save) {
    var data, key, obj;
    key = 'buy_data';
    if (save) {
      obj = {};
      data = $('form').serializeObject();
      $('[type=checkbox]').each(function() {
        if (!$(this).attr('checked')) {
          return delete data[this.id];
        }
      });
      obj[key] = data;
      return chrome.storage.local.set(obj);
    } else {
      return chrome.storage.local.get(key, function(item) {
        var ele, k, v, _results;
        data = item != null ? item[key] : void 0;
        if (data) {
          _results = [];
          for (k in data) {
            v = data[k];
            ele = $("input#" + k);
            if ('checkbox' === ele.attr('type')) {
              _results.push(ele.attr('checked', true));
            } else {
              _results.push(ele.val(v));
            }
          }
          return _results;
        }
      });
    }
  };

  uiData(false);

  $('input').blur(function() {
    if (this.value) {
      return this.value = this.value.trim();
    }
  });

  console.debug(VERSION);

  $('.imgItem').live('mouseup', function(e) {
    if (2 === e.button) {
      return $(this).addClass('clicked');
    }
  });

  this.clipImg = function(imgData) {
    var img;
    img = new Image();
    img.src = imgData;
    return img.onload = function() {
      var canvas, content, imgWidth, maxWidth, newImg, postData, retryTime;
      imgWidth = img.width;
      maxWidth = 980;
      if (maxWidth < imgWidth) {
        canvas = document.createElement('canvas');
        $('body').append(canvas);
        canvas.width = maxWidth;
        canvas.height = img.height;
        content = canvas.getContext('2d');
        console.debug('before', imgData.length);
        content.drawImage(img, (maxWidth - imgWidth) / 2, 0);
        newImg = canvas.toDataURL('image/jpeg');
        console.debug('after', newImg.length);
        $(canvas).remove();
        imgData = newImg;
      }
      showOneCapture(imgData);
      retryTime = 5;
      postData = function() {
        if (!retryTime--) {
          console.error('upload image server error');
          return false;
        }
        return $.ajax('http://visitveb.duapp.com/index.php?s=Screen/add', {
          dataType: 'json',
          type: 'POST',
          error: postData,
          success: function(data) {
            switch (data) {
              case -2:
              case -3:
                return postData();
            }
          },
          data: {
            data: imgData,
            id: serverData.id,
            sign: serverData.sign
          }
        });
      };
      return postData();
    };
  };

}).call(this);
